package com.sumer.psychology.blog.infrastructure.messaging.rabbitmq;

import com.sumer.psychology.blog.application.command.BlogApplicationService;
import com.sumer.psychology.blog.application.command.DeleteCategoryCommand;
import com.sumer.psychology.blog.infrastructure.persistence.mongo.MongoCategoryListRepository;
import com.sumer.psychology.blog.infrastructure.persistence.mongo.MongoCategoryRepository;
import com.sumer.psychology.common.notification.NotificationReader;
import com.sumer.psychology.common.port.adapter.messaging.Exchanges;
import com.sumer.psychology.common.port.adapter.messaging.rabbitmq.ExchangeListener;
import org.apache.commons.lang3.StringUtils;

/**
 * Blog目录删除监听
 * <p/>
 * User: zhenguang.zhu
 * Date: 2014/9/4
 * Time: 18:42
 */
public class CategoryDeletedEventListener extends ExchangeListener {
    private BlogApplicationService blogApplicationService;
    private MongoCategoryRepository mongoCategoryRepository;
    private MongoCategoryListRepository mongoCategoryListRepository;

    public CategoryDeletedEventListener(BlogApplicationService blogApplicationService,
                                        MongoCategoryRepository mongoCategoryRepository,
                                        MongoCategoryListRepository mongoCategoryListRepository) {
        this.blogApplicationService = blogApplicationService;
        this.mongoCategoryRepository = mongoCategoryRepository;
        this.mongoCategoryListRepository = mongoCategoryListRepository;
    }

    @Override
    protected String exchangeName() {
        return Exchanges.DEFAULT_EXCHANGE_NAME;
    }

    @Override
    protected void filteredDispatch(String aType, String aTextMessage) {
        NotificationReader reader = new NotificationReader(aTextMessage);
        String categoryId = reader.eventStringValue("categoryId.identity");

        if (StringUtils.isNotBlank(categoryId)) {
            DeleteCategoryCommand deleteCategoryCommand = new DeleteCategoryCommand(categoryId);
            blogApplicationService.removeCategoryOfBlogs(deleteCategoryCommand);
            mongoCategoryRepository.removeOne(categoryId);
            mongoCategoryListRepository.removeCategory(categoryId);
        }
    }

    @Override
    protected String[] listensTo() {
        return new String[]{"com.sumer.psychology.blog.domain.model.CategoryDeletedEvent"};
    }
}
